import { Component, OnInit } from '@angular/core';
import { Observable, fromEvent, interval, of } from 'rxjs';
import { fromPromise } from 'rxjs/internal-compatibility';
import { take, filter, map } from 'rxjs/operators';
@Component({
  selector: 'app-rxjs',
  templateUrl: './rxjs.component.html',
  styleUrls: ['./rxjs.component.less']
})
export class RxjsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    //方式1
    let ob1 = new Observable(observer => {

      setInterval(() => {

        //observer.next({success:true,data:'next ok'});
        //observer.error({success:false,data:-1});
        observer.complete();

      }, 3000);

    });

    let subscribtion = ob1.subscribe((data) => {
      console.log(data);
    }, (data) => {
      console.log(data, 'error')
    }, () => {
      console.log('complete');
    });


    let ob2 = fromPromise(fetch('assets/data.json').then(r => r.json()));
    ob2.subscribe({
      next(data) {
        let r = data;
        console.log(r);
      },
      error() {
        console.log('ajax error')
      }
    });


    let ob3 = fromEvent(document, 'click');
    let s3 = ob3.subscribe((ev: MouseEvent) => {
      console.log(ev.clientX);
      s3.unsubscribe();
    });


    let ob4 = interval(2000).pipe(
      take(4)
    );
    ob4.subscribe(num => {
      console.log(num);
    });


    let ob5 = of(1, 2, 3, 4, 5).pipe(
      filter(n => n % 2 !== 0),
      map(n=>n*n)
    );
    ob5.subscribe(num => {
      console.log('num' + num);
    });



  }

}
